
"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
def index():
    if request.args and request.args[0] != None:
        session.problemid = int(request.args[0])
    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))
    data = problem.responseArray()
    from gluon.contenttype import contenttype
    response.headers['Content-Type'] = contenttype('.csv')
    t = str(request.now)
    label = problem.getLabel()
    filename = '-'.join((label+'-'+t+'.csv').split(' '))
    response.headers['Content-disposition'] = \
        'attachment; filename=%s' % filename
    
    from csv import writer
    from StringIO import StringIO
    out = StringIO()
    w = writer(out)
    for row in data:
        w.writerow(row)
    return out.getvalue()

@auth.requires_login()
def lorem():
    """
    Development-only controller that creates a new problem containing demo text
    and results that illustrate the various possible outcomes of user responses
    to problems. Primarily for testing and creating example problems.
    """
    #if not PTCFG.development:
    #    message="Sorry, lorem is for development only."
    #    return(dict(message=message))
    from random import choice, random as r

    t = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat bibendum diam, at rhoncus dolor rhoncus nec. Donec ullamcorper, lectus vitae ornare porta, lectus nisl semper orci, ac pretium eros mi a diam. Cras dignissim, erat sit amet tempor interdum, urna neque auctor sem, sit amet luctus ipsum urna a erat. Nam egestas augue enim, vel scelerisque enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque ultrices suscipit porttitor. Sed ultricies vehicula bibendum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor nibh nec est rutrum congue. Curabitur luctus malesuada mattis. Sed dapibus, nunc eu fringilla volutpat, est lectus rhoncus libero, at molestie nisl lacus ac ante. Integer consectetur quam ac lacus ultrices a condimentum ligula feugiat. Curabitur sed turpis purus. Phasellus id sem felis, vitae ornare velit.

Sed in odio vitae enim suscipit lobortis. Maecenas nibh odio, cursus a euismod quis, egestas sit amet justo. Sed tincidunt mattis auctor. Cras a urna non erat aliquet tempor. Quisque justo tellus, ornare id ultrices ullamcorper, bibendum at quam. Cras tincidunt nunc ut enim ullamcorper volutpat. Suspendisse potenti. Quisque pellentesque augue vitae libero tempus pretium. Nulla porttitor lacinia dui vel pulvinar. Cras nec ante nunc, quis auctor nunc. Sed at eros ante, nec semper neque. Quisque scelerisque rhoncus leo, gravida euismod ante rutrum sed. Donec eu est tristique enim posuere congue. Nulla facilisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In faucibus imperdiet quam. Nam ligula elit, eleifend vel vulputate at, interdum sit amet est.

Aliquam pellentesque tempor nisi, a malesuada magna dignissim ac. Proin consectetur, est a condimentum varius, diam augue pulvinar ligula, id auctor justo augue sed ipsum. Aenean a dignissim est. Donec in libero turpis, sed venenatis mauris. Sed nec libero est. Duis sed dolor metus, et cursus sapien. Ut nulla mi, malesuada quis laoreet at, consequat eu lorem. In hac habitasse platea dictumst. Donec tincidunt auctor orci, eget congue massa condimentum a. Aliquam sit amet porta quam. Nulla magna metus, pharetra a hendrerit ut, fermentum et mi. Praesent nec sapien purus. Nulla quis metus velit. Quisque varius gravida massa, commodo lacinia neque tempor vel. Ut erat risus, tempus viverra gravida vitae, rhoncus sed nisi. Cras ac sollicitudin risus. Sed congue malesuada ornare. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

Ut mollis blandit eros, eu molestie orci pharetra id. Aenean elementum odio ac sapien luctus in consectetur turpis volutpat. Curabitur ac urna at odio commodo viverra. Nulla elementum elementum iaculis. Etiam velit nisl, suscipit non posuere sit amet, porttitor ac mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris diam dolor, luctus at ultricies eget, tempus eu ligula. Curabitur ac ipsum sapien. Etiam sollicitudin, justo in consequat adipiscing, eros tortor blandit lacus, id imperdiet justo sem at leo. Etiam et massa ante. Ut fermentum massa at dolor pretium facilisis. Pellentesque feugiat sodales leo id luctus. Sed et ligula vitae neque rhoncus volutpat et vitae nisi. Nulla non enim nisi. In non enim bibendum ligula hendrerit rutrum nec sed lacus. Maecenas sit amet nisl in ligula volutpat luctus. Maecenas id velit diam, eu mattis sem.

Etiam ullamcorper ligula non nisi pellentesque et eleifend nibh tristique. Maecenas sagittis tortor ornare neque volutpat mattis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales aliquet nulla, semper tristique dolor tempor nec. Donec accumsan ultricies pharetra. Phasellus tempus eros sit amet lorem sollicitudin pretium. Sed congue sodales aliquam. Cras a pellentesque tellus. Donec sit amet neque nibh, non tempus lacus. Suspendisse potenti. Proin in quam vel arcu scelerisque luctus. Praesent malesuada elementum elementum. Curabitur facilisis diam eget justo porttitor non molestie tortor commodo. Maecenas faucibus elementum leo, blandit interdum magna ullamcorper a. Morbi ut sem sit amet odio egestas laoreet. Nam quis dolor cursus metus eleifend iaculis sit amet nec urna. Phasellus ut eleifend tortor. Integer placerat condimentum augue, eget vulputate elit tristique nec. Vivamus lectus risus, auctor ullamcorper porta a, consectetur placerat nisi.
""".split('\n\n')

    assert len(t)==5
    def item(title):
        txt = choice(t)
        return "<p>%(title)s</p>\n\n<p>%(txt)s</p>"%locals()

    # Create a problem
    description = item("Tabellae")
    s0 = item("Lorem Ipsum")
    c0=item("Sagaciter")
    problem = ptproblem.Problem(description,
        creatorid=auth.user.id,
        defaultsolutiontext=s0,
        defaultcriteriontext=c0,)

    problem.setSynonyms(PTCFG.synonyms)

    ## insert it into the database
    id = _addNewProblemToDb(problem)     
    # Fill it with some appropriately titled solutions and criteria
    S = ptproblem.Solution
    C = ptproblem.Criterion
    problem.addSolution(S(item("Sed In Odio")))
    problem.addSolution(S(item("In Media Res")))
    problem.addSolution(S(item("Multitudinem Diviso")))
    problem.addSolution(S(item("Unum Fracto")))

    problem.addCriterion(C(item("Populus Videor")))
    problem.addCriterion(C(item("Nidor")))

    mergeadditions(problem,id)
    problem = loadProblem(id)

    # Generate some corresponding responses for 20 participants
    def rndm(mn,mx):
        return mn + r()*(mx-mn)

    def sresponse(t):
        if "Lorem Ipsum" in t:                  # Very positive
            return rndm(0.7,1.0)
        elif "In Media Res" in t:               # Ho Hum
            return rndm(-0.23,0.23)
        elif "Multitudinem Diviso" in t:        # Random results
            return rndm(-1.,1.)
        elif "Sed In Odio" in t:                # Very negative
            return rndm(-1.0, -0.7)
        elif "Unum Fracto" in t:                # Controversial
            sgn = choice((-1,1))
            ofst = 0.9*sgn
            return rndm(-0.1 + ofst, 0.1 + ofst)

    def cresponse(t):
        if "Sagaciter" in t:
            return rndm(0.6,1.0)
        elif "Populus Videor" in t:
            ofst = choice((-0.425, 0.425))
            return rndm(0.425 + ofst, 0.575 + ofst)
        elif "Nidor" in t:
            return rndm(0.0,0.2)

    for i in xrange(20):
        uid = i + 100000                        # avoid conflict with 
                                                # real user id's.
        problem.addTeamMember(uid)
        mergeadditions(problem,id)
        problem = loadProblem(id)

        c = dict()
        s = dict()
        cd = dict()
        sd = dict()
        for sid in problem.solutions:
            txt = ptproblem.mkLabel(problem.solutions[sid].text)
            s[sid] = [(cid,sresponse(txt)) for cid in problem.criteria]
            sd[sid] = False
        for cid in problem.criteria:
            txt = ptproblem.mkLabel(problem.criteria[cid].text)
            c[cid] = cresponse(txt)
            cd[cid] = False

        problem.acceptResponses(uid, c, s, cd, sd)
                
        mergeresponses(uid,problem,id)
        problem = loadProblem(id)

    redirect(URL(r=request,c='choose',f='index'))
    # Redirect to response page.
    
